import React, { useEffect, useState, useCallback } from 'react';
import { useStore } from '@/hooks';
import { Button, Divider, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import { column } from '../stores/definitions';
import TauTable from '@/components/TauTable';
import ChargeForm from './ChargeForm';

const CurrentTable = ({ data }) => {
  const { busStationStore: store } = useStore();
  const [state, setState] = useState([]);
  const [currentPage, setCurrentPage] = useState(0); // 默认页数
  const [pageSize, setPageSize] = useState(10); // 每页显示的数据数量
  const [curCharge, setCurCharge] = useState();
  const [idx, setIdx] = useState();

  useEffect(() => {
    if (data) {
      const tfData = data.map((p) => ({
        ...p,
        proKey: `${p.companyId}-${p.stationId}`,
      })) || [];
      setState(tfData);
    }
  }, [data]);

  useEffect(() => {
    store.currentStationInfos = state;
  }, [state]);

  // 分页数据
  const getCurrentPageData = () => {
    const startIndex = currentPage * pageSize;
    const endIndex = startIndex + pageSize;
    return state.slice(startIndex, endIndex);
  };

  const currentPageData = getCurrentPageData();

  const handleDeleteSite = (i) => {
    setState((pre) => {
      const clone = [...pre];
      clone.splice(i, 1);
      return clone;
    });
  };

  const handleCurCharge = useCallback((values) => {
    setCurCharge({
      values,
    });
  }, [setCurCharge]);


  const chargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    setState((pre) => {
      const newCharge = [...pre];
      newCharge[idx] = values;
      return newCharge;
    });
    setCurCharge(false);
  };

  return (
    <>
      <TauTable
        primaryKey="proKey"
        tableLayout="fixed"
        currentPage={currentPage}
        pageSize={pageSize}
        total={state.length}
        sort={store.tableSort}
        onFetch={({ page, size }) => {
          setCurrentPage(page);
          size && setPageSize(size);
        }}
        loading={store.other_loading}
        dataSource={currentPageData}
        onRowClick={(_, index) => setIdx(index)}
        columns={[
          { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.currentIdx(i, currentPage, pageSize) },
          column('companyName', {}),
          column('stationName', {}),
          column('stationId', { width: 80 }),
          column('tableKind', { width: 100 }),
          column('addressText', {}),
          column('longLat', {}),
          column('link', {}),
          {
            title: t`操作`,
            dataIndex: 'currentTableNumber',
            cell: (__, i, r) => {
              return (
                <>
                  <Button type="primary" text onClick={() => handleCurCharge(r)}>{t`编辑`}</Button>
                  <Divider direction="ver" />
                  <Button text type="primary" style={{ color: 'red' }} onClick={() => handleDeleteSite(i, r)} >{t`移除`}</Button>
                </>
              );
            },
          },
        ]}
      />
      <Dialog
        visible={!!curCharge}
        onCancel={() => setCurCharge(false)}
        onClose={() => setCurCharge(false)}
        title={t`编辑内容`}
        style={{ width: '30%' }}
        footer={null}
      >
        <ChargeForm
          data={curCharge}
          onSubmit={(r, errors) => chargeOnSubmit(r, errors)}
          onCancel={() => setCurCharge(false)}
        />
      </Dialog>
    </>
  );
};

export default observer(CurrentTable);
